package com.wishu.finance.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wishu.finance.domain.*;
import com.wishu.finance.enums.*;
import com.wishu.finance.mapper.TCfContractMapper;
import com.wishu.finance.mapper.TCwReceiptPlanMapper;
import com.wishu.finance.mapper.TJrProductMapper;
import com.wishu.finance.mapper.TJrRentInstallmentMapper;
import com.wishu.finance.service.TJrRentInstallmentService;
import com.wishu.finance.utils.BeanUtils;
import com.wishu.finance.utils.MyJinRongUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;

/**
 * @author 25813
 * @description 针对表【t_jr_rent_installment(房租分期申请)】的数据库操作Service实现
 * @createDate 2023-04-28 19:16:34
 */
@Service
public class TJrRentInstallmentServiceImpl extends ServiceImpl<TJrRentInstallmentMapper, TJrRentInstallment>
        implements TJrRentInstallmentService {

    @Resource
    TCfContractMapper cfContractMapper;
    @Resource
    TCwReceiptPlanMapper receiptPlanMapper;
    @Resource
    TJrProductMapper jrProductMapper;
    @Resource
    TJrRentInstallmentMapper rentInstallmentMapper;

    @Override
    public IPage<JrRentInstallmentResponseDto> selectPageVo(IPage<?> page, JrRentInstallmentSearch jrRentInstallmentSearch) {
        return baseMapper.selectPageVo(page, jrRentInstallmentSearch);
    }

    @Override
    public JrRentInstallmentDetailsResponseDto selectInstallmentDetails(Long id) {
        return baseMapper.selectInstallmentDetails(id);
    }

    /**
     * 查询 - 合同详情
     *
     * @throws ParseException
     */
    @Override
    public ContractDetailsResponseDTO getContract(Integer contractId) {
        TCfContract c = cfContractMapper.selectById(contractId);
        ContractDetailsResponseDTO res = new ContractDetailsResponseDTO();
        res.setContractId(c.getId());
        res.setOutOrderNo(c.getCfContractNo());
        res.setRoomName(c.getRoomName());
        res.setHouseId(c.getHouseId());
        res.setTenantName(c.getTenantName());
        res.setTenantPhone(c.getTenantPhone());
        res.setTenantCardNo(c.getTenantCardNo());
        res.setRoomCode(c.getRoomCode());
        res.setRealEstateInfo(c.getRoomName());
        res.setRoomId(c.getRoomId());
        // 查询租房分期
        List<TCwReceiptPlan> recList = getCwReceiptPlanList(c.getId());
        double balance = 0;
        Date startDate = null;
        if (recList.size() > 0) {
            for (TCwReceiptPlan r : recList) {
                balance = MyJinRongUtils.add(balance, r.getPaymentAmount().doubleValue());
                if (null == startDate) {
                    startDate = r.getPaymentDaysBegin();
                } else if (1 == startDate.compareTo(r.getPaymentDaysBegin())) {
                    startDate = r.getPaymentDaysBegin();
                }
            }
        }
        Date endDate = c.getEndDate();
        res.setEndDate(endDate);
        res.setStartDate(startDate);
        List<MyJinRongUtils.KeyValueForDate> splitMonth = MyJinRongUtils.getSplitMonthForDate(startDate, endDate);
        if (null == splitMonth) {
            res.setPeriods(0);
        } else {
            res.setPeriods(splitMonth.size());
        }
        int count = getCwReceiptPlanPaidCount(contractId.longValue());
        if (count == 0) {
            double div = MyJinRongUtils.div(balance, splitMonth.size(), 2);
            balance = MyJinRongUtils.sub(balance, div);
            Calendar cl = Calendar.getInstance();
            cl.setTime(res.getStartDate());
            cl.add(Calendar.MONTH, 1);
            res.setStartDate(cl.getTime());
            res.setBalance(balance);
            res.setPeriods(splitMonth.size() - 1);
        } else {
            res.setBalance(balance);
        }
        return res;
    }

    /**
     * 查询金融产品
     */
    @Override
    public List<ProductResponseDTO> listProduct() {
        List<ProductResponseDTO> resList = new ArrayList<>();
        ProductResponseDTO res = null;
        Map<String, Object> param = new HashMap<>();
        param.put("del_flg", 0);
        param.put("jr_product_type", 1);
        List<TJrProduct> list = jrProductMapper.selectByMap(param);
        for (TJrProduct p : list) {
            res = new ProductResponseDTO();
            res.setId(p.getId());
            res.setName(p.getJrProductName());
            res.setCreditLine(p.getCreditLine().doubleValue());
            res.setInstalmentPeriod(p.getInstalmentPeriod());
            resList.add(res);
        }
        return resList;
    }

    /**
     * 校验 - 金融产品
     */
    @Override
    public boolean checkProduct(CheckProductRequestBeanDTO dto) {
        boolean flag = false;
        TJrProduct product = jrProductMapper.selectById(dto.getProductId());
        Long instalmentPeriod = product.getInstalmentPeriod();
        if (-1 == instalmentPeriod) {
            return true;
        }
        if (instalmentPeriod >= dto.getPeriods()) {
            flag = true;
        }
        return flag;
    }

    /**
     * 查询 - 计算列表
     */
    @Override
    public SearchRentInstallmentDetailResponseDTO getRentInstallmentDetail(SearchRentInstallmentDetailRequestDTO dto) {
        SearchRentInstallmentDetailResponseDTO res = null;
        // 查询金融产品
        TJrProduct product = jrProductMapper.selectById(dto.getProductId());
        dto.setCreditLine(product.getCreditLine().doubleValue());
        try {
            res = MyJinRongUtils.getComputeFQ(dto);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        res.setProductId(dto.getProductId());
        res.setId(dto.getContractId());
        return res;
    }

    /**
     * 保存 - 分期申请
     */
    @Override
    public void saveRentInstallment(SaveRentInstallmentRequestDTO dto) {
        TJrRentInstallment entity = new TJrRentInstallment();
        Date nowDate = new Date();
        BeanUtils.copy(dto, entity);
        entity.setReLeaseCount(dto.getReLeaseCount());
        entity.setInInterestCount(dto.getInInterestCount());
        entity.setSerCharge(dto.getSerCharge().intValue());
        entity.setCoHirerentCount(dto.getCoHirerentCount());
        entity.setBussinessId(dto.getBusinessId().toString());
        entity.setRate(dto.getRate());
        entity.setTenantRate(dto.getTenantRate());
        entity.setBusinessRate(dto.getBusinessRate());
        entity.setServiceFee(dto.getServiceFee().intValue());
        entity.setLoanAmount(dto.getLoanAmount());
        entity.setMonthLimit(dto.getMonthLimit());
        entity.setJrProductId(dto.getJrProductId());
        entity.setCfContractId(dto.getContractId());
        TJrProduct jrEntity = jrProductMapper.selectById(dto.getJrProductId());
        if (jrEntity.getCompanyName().equals("应花")) {
            entity.setApplyState(2);
        } else {
            entity.setApplyState(1);
        }
        entity.setUpdateTime(nowDate);
        entity.setUpdateUserid(dto.getLoginUserId());
        entity.setCreateUserid(dto.getLoginUserId());
        entity.setCreateTime(nowDate);
        entity.setRentInstallmentOrderNo(UUID.randomUUID().toString());
        entity.setDeptId(Long.valueOf(169));
        entity.setDeptNo("");
        rentInstallmentMapper.insert(entity);
        // 更新合同表
        TCfContract contract = cfContractMapper.selectById(dto.getContractId());
        contract.setFreezeStatus(1);// rent_installment_flg
        contract.setRentInstallmentFlg(1);
        contract.setUpdateTime(nowDate);
        contract.setUpdateUserid(dto.getLoginUserId());
        cfContractMapper.updateById(contract);
        // 更新租房分期
        List<TCwReceiptPlan> recList = this.getCwReceiptPlanList(dto.getContractId());
        for (TCwReceiptPlan r : recList) {
            r.setSkStatus(SkStatusEnum.YDJ.getIndex());// 冻结
            r.setUpdateTime(nowDate);
            r.setUpdateUserid(dto.getLoginUserId());
            receiptPlanMapper.updateById(r);
        }
    }

    // 查询 - 收款计划
    private List<TCwReceiptPlan> getCwReceiptPlanList(Long cid) {
        Map<String, Object> param = new HashMap<>();
        param.put("contract_type", ContractTypeEnum.CF.getIndex());
        param.put("contract_id", cid);
        param.put("receipt_type", ReceiptTypeEnum.FZ.getIndex());
        param.put("sk_status", SkStatusEnum.WSK.getIndex());
        param.put("bill_type", CollectionPlanZdType.PTZD.getIndex());
        param.put("item_type", BusinessCostTypesEnum.ZUJIN.getIndex());
        return receiptPlanMapper.selectByMap(param);
    }

    // 查询 - 收款计划
    private int getCwReceiptPlanPaidCount(Long cid) {
        Map<String, Object> param = new HashMap<>();
        param.put("contract_type", ContractTypeEnum.CF.getIndex());
        param.put("contract_id", cid);
        param.put("receipt_type", ReceiptTypeEnum.FZ.getIndex());
        param.put("sk_status", SkStatusEnum.YSK.getIndex());
        param.put("bill_type", CollectionPlanZdType.PTZD.getIndex());
        param.put("item_type", BusinessCostTypesEnum.ZUJIN.getIndex());
        return receiptPlanMapper.selectByMap(param).size();
    }
}




